package com.example.springbootbabyu.service.impl;

import com.example.springbootbabyu.entity.LoginDTO;
import com.example.springbootbabyu.entity.LoginVO;
import com.example.springbootbabyu.entity.RegisterDTO;
import com.example.springbootbabyu.mapper.UserMapper;
import com.example.springbootbabyu.service.UserService;

import com.example.springbootbabyu.utils.JwtTokenUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 功能
 * 作者：梦天
 * 日期：2025/4/19 21:24
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final JwtTokenUtil jwtTokenUtil;
    private UserServiceImpl(UserMapper userMapper, JwtTokenUtil jwtTokenUtil) {
        this.userMapper = userMapper;
        this.jwtTokenUtil = jwtTokenUtil;
    }
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 查询用户
        LoginVO user = userMapper.selectByAccount(loginDTO.getAccount(), loginDTO.getPassword());
        if (user == null) {
            return null;
        }

        String token = jwtTokenUtil.generateToken(user.getId(), user.getAccount());
        user.setToken(token);
        log.info("登录成功，用户：{}", user);
        // 转换结果对象
        return user;
    }

    @Override
    public Boolean register(RegisterDTO registerDTO) {
        // 注册用户
        try {
            log.info("注册用户：{}", registerDTO);
            userMapper.insert(registerDTO);
            return true;
        } catch (Exception e) {
            log.error("注册失败，原因：{}", e.getMessage());
            return false;
        }
    }
}